<script setup>
import { ref, computed } from 'vue'
import { addItemService, updateItemService } from '@/api/item.js'
import { fileUploadService } from '@/api/common.js'
import { Plus } from '@element-plus/icons-vue'
import { imageUrlToFile } from '@/utils/request'
import ItemCategorySelect from './ItemCategorySelect.vue'

// 控制抽屉的显示与隐藏
const visibleDrawer = ref(false)

const defaultDTO = {
  name: null, // 物品名称
  itemCategoryId: null, // 物品类别id
  brand: null, // 品牌
  price: null, // 物品价格
  minStock: null, // 最小库存
  description: null, // 物品描述
  picUrl: null // 物品图片链接
}

const itemDTO = ref({ ...defaultDTO })

// 价格转换
const priceConverter = computed({
  get() {
    if (itemDTO.value.price) {
      return itemDTO.value.price / 100
    } else {
      return null
    }
  },
  set(value) {
    itemDTO.value.price = value * 100
  }
})

// 向外暴露方法
const open = (row) => {
  visibleDrawer.value = true // 打开抽屉
  if (row.id) {
    itemDTO.value = {
      id: row.id,
      name: row.name,
      itemCategoryId: row.itemCategoryId,
      brand: row.brand,
      price: row.price,
      minStock: row.minStock,
      description: row.description,
      picUrl: row.picUrl
    }
  } else {
    itemDTO.value = { ...defaultDTO }
  }
  imgInfo.value.name = ''
  imgInfo.value.url = ''
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (imgInfo.value.name) {
    // 将网络图片地址转换为file对象
    const file = await imageUrlToFile(imgInfo.value.url, imgInfo.value.name)
    const res = await fileUploadService(file)
    itemDTO.value.picUrl = res.data.data
  }
  if (itemDTO.value.id) {
    await updateItemService(itemDTO.value)
    ElNotification({
      title: '修改成功',
      type: 'success'
    })
  } else {
    await addItemService(itemDTO.value)
    ElNotification({
      title: '新增成功',
      type: 'success'
    })
  }
  visibleDrawer.value = false
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDrawer.value = false
  itemDTO.value = { ...defaultDTO }
}

// 文件上传
const imgInfo = ref({
  name: '', // 文件名
  url: '' // 网络图片地址
})
const getImageUrl = (uploadFile) => {
  imgInfo.value.name = uploadFile.name
  imgInfo.value.url = URL.createObjectURL(uploadFile.raw) // 预览图片
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer v-model="visibleDrawer" :title="itemDTO.id ? '修改物品信息' : '新增物品'">
    <el-form :model="itemDTO" ref="formRef" label-width="auto">
      <el-form-item label="物品名称" prop="name">
        <el-input v-model="itemDTO.name" placeholder="请输入物品名称"></el-input>
      </el-form-item>
      <el-form-item label="物品图片" prop="picUrl">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="getImageUrl"
        >
          <img
            v-if="itemDTO.picUrl || imgInfo.url"
            :src="imgInfo.url ? imgInfo.url : itemDTO.picUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="物品类别" prop="itemCategoryId">
        <item-category-select v-model="itemDTO.itemCategoryId" width="100%" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="itemDTO.brand" placeholder="请输入品牌"></el-input>
      </el-form-item>
      <el-form-item label="物品价格" prop="price">
        <el-input-number
          v-model="priceConverter"
          placeholder="请输入物品价格(元/件)"
          :min="0"
          :precision="2"
          :step="0.1"
          style="width: 240px"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="最小库存" prop="minStock">
        <el-input-number
          v-model="itemDTO.minStock"
          placeholder="请输入最小库存"
          :min="0"
          style="width: 240px"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="物品描述" prop="description">
        <el-input v-model="itemDTO.description" placeholder="请输入物品描述"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="handleSubmit">提交</el-button>
        <el-button type="info" plain @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
    }
  }
}
</style>
